package com.nicole.reqresp.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author  xiaoying
 */
@Slf4j
public class MyRequestBodyReaderWrapper extends HttpServletRequestWrapper {
    /**
     * 存放JSON数据主体
     */
    private final byte[] body;
    /** 缓存 BODY 的输入流，供接口读取 BODY **/
    private final MyInputStream inputStream;
    public MyRequestBodyReaderWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = StreamUtils.copyToByteArray(request.getInputStream());
        inputStream = new MyInputStream(body);
    }


    @Override
    public ServletInputStream getInputStream() throws IOException {
       if(null != inputStream){
           return inputStream;
       }
       return super.getInputStream();
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
    /**
     * 获取请求Body
     */
    public String getBody(ServletRequest request) {
      return new String(body);
    }
}
